import { type PaginationProps } from "@pureadmin/table";
import { getKeyList } from "@pureadmin/utils";
//import { useDataListStoreHook } from "@/store/modules/datalist"

import {
  reactive,
  ref,
  Ref,
  toRaw,
  onBeforeMount,
  h,
  watch
  //computed
} from "vue";
import {
  getModeInfo,
  getDataLists,
  delFormData,
  exeFormFunApi,
  importData,
  importExlData,
  excelData,
  getRolesList
} from "@/api/dataList";
import { message } from "@/utils/message";
import router from "@/router";
import { addDialog, ButtonProps, closeDialog } from "@/components/ReDialog";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import type { reqExeFun } from "./types";
import editForm from "../form.vue";
import dialog from "../dialog.vue";
//import { number } from "echarts";

export function useDataList(tableRef: Ref) {
  const loading = ref(true);
  const oneModel = ref();
  const dataList = ref([]);
  const appID = ref();
  const modeID = ref();
  const isData = ref(false);
  const funList = ref([]);
  const dialogRef = ref();
  const fileList = reactive([]);
  const formData = new FormData();
  const fileUpload = ref();
  const fileUploadExl = ref();
  const parentCode = ref("");
  //const imgCount = ref(1);
  //const isSuccess = ref(false);
  const Myoptions = ref();
  const Myindex = ref();
  const editCode = ref();
  const isDown = ref(false);

  const usubID = ref(0);
  const msubID = ref(0);
  const currentRow = ref();
  //const imgList = ref([]);
  //const mySub = useDataListStoreHook();

  let formFunList = [] as Array<ButtonProps>;

  const filterList = ref([]);
  const editFormRef = ref();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const reqFun = reactive<reqExeFun>({
    funID: 0,
    tableName: "",
    ids: "",
    currText: "",
    contrlID: 0,
    contrText: ""
  });

  const form = reactive({
    // 左侧部门树的id
    deptId: 0,
    appName: "",
    isShow: "",
    subID: 0,
    onePage: pagination,
    sortName: "id",
    editTable: "",
    sort: true,
    filterArr: [],
    searchKey: "",
    modeID: 0,
    parentID: 0
  });

  const myProp = reactive({
    modeID: modeID,
    rsID: 0,
    isSearch: false,
    tableName: "",
    isSuccess: false,
    isSheng: false,
    editCode: 0,
    paretCode: ""
  });

  const ctrButton = reactive({
    isAdd: false,
    isDel: false,
    isSearch: false,
    isUpdate: false,
    isImport: false,
    isExport: false,
    isSheng: false,
    isUploadExl: false
  });
  const links = ref([]);
  const tempLink = ref([]);

  const columns = reactive<TableColumnList>([
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      sortable: true,
      reserveSelection: true // 数据刷新后保留选项
    }
  ]);

  onBeforeMount(async () => {
    appID.value = router.currentRoute.value.name;
    init(0, 0);
  });

  //初始化表格数据
  async function init(subid, pid) {
    dataList.value = [];
    const Result = await getModeInfo({
      appID: appID.value,
      clientID: 1,
      subID: subid
    });

    if (Result.isSuccess) {
      columns.splice(1, columns.length - 1);
      oneModel.value = Result.result;
      form.deptId = appID.value;
      form.parentID = pid;
      form.modeID = modeID.value;
      editCode.value = oneModel.value.editCode;
      modeID.value = oneModel.value.oneModel.id;
      form.appName = oneModel.value.oneModel.showTable;
      form.editTable = oneModel.value.oneModel.editTable;
      msubID.value = oneModel.value.oneModel.modeType;

      if (msubID.value != 0) {
        isDown.value = true;
      }
      oneModel.value.tableHeads.forEach(element => {
        columns.push({
          sortable: "custom",
          label: element.label,
          prop: element.prop,
          width: element.width,
          align: element.align
        });
        // columns.push(toRaw(element));
      });

      tempLink.value = [];
      tempLink.value = links.value;

      const oneK = links.value.filter(
        item => item.id == oneModel.value.oneModel.id
      );
      if (oneK.length == 0) {
        links.value.push({
          id: oneModel.value.oneModel.id,
          tableName: oneModel.value.oneModel.showTable,
          pageIndex: form.onePage.currentPage,
          row: null,
          parentID: pid
        });
      } else {
        form.onePage.currentPage = oneK[0].pageIndex;
        links.value = [];
        //tempLink.value.forEach(el => {
        for (let i = 0; i < tempLink.value.length; i++)
          if (tempLink.value[i].id != oneModel.value.oneModel.id) {
            links.value.push({
              id: tempLink.value[i].id,
              tableName: tempLink.value[i].tableName,
              pageIndex: tempLink.value[i].pageIndex,
              row: tempLink.value[i].row,
              parentID: tempLink.value[i].parentID
            });
          } else {
            const oneObj = {
              id: tempLink.value[i].id,
              tableName: tempLink.value[i].tableName,
              pageIndex: tempLink.value[i].pageIndex,
              row: tempLink.value[i].row,
              parentID: tempLink.value[i].parentID
            };
            links.value.push(oneObj);
            break;
          }
        // })
      }

      //标准操作配置
      ctrButton.isAdd = oneModel.value.isAdd;
      ctrButton.isDel = oneModel.value.isDel;
      ctrButton.isUpdate = oneModel.value.isUpdate;
      ctrButton.isUploadExl = oneModel.value.isUploadExl;
      ctrButton.isSearch = oneModel.value.isSearch;
      ctrButton.isImport = oneModel.value.isImport;
      ctrButton.isExport = oneModel.value.isExport;
      ctrButton.isSheng = oneModel.value.isSheng;

      funList.value = oneModel.value.appFunctions;
      filterList.value = oneModel.value.filterList;
      if (oneModel.value.isContrl) {
        columns.push({
          label: "操作",
          fixed: "right",
          width: 220,
          slot: "operation"
        });
      }
      await onSearch();
      isData.value = true;
    } else {
      message(Result.msg, { type: "error" });
    }
  }

  //编辑页面权限设置
  function getFormFunList(ctrButton, isNew, ids) {
    //单个表单的配置
    if (ctrButton.isAdd || ctrButton.isUpdate || ctrButton.isSheng) {
      formFunList = [];
      formFunList.push({
        label: "保存",
        type: "primary",
        icon: useRenderIcon("ep:circle-check"),
        btnClick: async ({ dialog: { options, index } }) => {
          const dd = editFormRef.value;
          Myoptions.value = options;
          Myindex.value = index;
          watch(
            () => dd.isSuccess,
            () => {
              closeDialog(Myoptions.value, Myindex.value);
            }
          );
          await dd.saveJson();
        }
      });
    }
    if (ctrButton.isDel && isNew != 1) {
      formFunList.push({
        label: "删除",
        type: "danger",
        icon: useRenderIcon("ep:delete"),
        btnClick: ({ dialog: { options, index } }) => {
          //const dd = editFormRef.value;
          //dd.saveJson();
          onbatchDel(false, ids);
          closeDialog(options, index);
        }
      });
    }

    if (ctrButton.isSearch || ctrButton.isSheng) {
      formFunList.push({
        label: "关闭窗口",
        type: "primary",

        btnClick: ({ dialog: { options, index } }) => {
          closeDialog(options, index);
        }
      });
    }

    //遍历其它功能
    oneModel.value.appFunctions.forEach(element => {
      if (element.showType == 1) {
        formFunList.push({
          label: element.funName,
          type: "success",
          icon: useRenderIcon(element.funIcon),
          btnClick: () => {
            exeFormFun(ids, element);
          }
        });
      }
    });
  }

  function getImage(row: string) {
    const lastIndex = row.lastIndexOf(".");
    const result = row.substring(lastIndex + 1);

    let isRadio = false;
    switch (result) {
      case "mp4":
      case "avi":
      case "mov":
      case "wmv":
      case "flv":
        isRadio = true;
        break;
    }
    return isRadio;
  }

  //查询数据
  async function onSearch() {
    loading.value = true;
    form.filterArr = [];
    form.subID = usubID.value;
    filterList.value.forEach(element => {
      if (element.filterValue != null && element.filterValue != "") {
        form.filterArr.push({
          key: element.filterField,
          value: element.filterValue
        });
      }
    });
    let myRow = null;
    const oneK = links.value.filter(
      item => item.id == oneModel.value.oneModel.id
    );
    if (oneK.length != 0) {
      form.parentID = oneK[0].parentID;
      myRow = oneK[0].row;
    }

    const Result = await getDataLists(toRaw(form));
    if (Result.isSuccess) {
      dataList.value = JSON.parse(Result.data);
      if (myRow != null) {
        currentRow.value = myRow;
      }
      if (Result.msg != null) {
        parentCode.value = Result.msg;
      }
      pagination.total = Result.onePage.total;
      pagination.pageSize = Result.onePage.pageSize;
      pagination.currentPage = Result.onePage.currentPage;
    } else {
      message(Result.msg, { type: "error" });
    }
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  //分页选择
  async function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    const oneK = links.value.filter(
      item => item.id == oneModel.value.oneModel.id
    );
    if (oneK.length != 0) {
      oneK[0].pageIndex = val;
    }

    await onSearch();
  }
  //页面记录数改变
  async function handleSizeChange(val: number) {
    pagination.pageSize = val;
    await onSearch();
  }

  //删除操作
  async function handleDelData(ids: string) {
    console.log(ids, "删除");
  }

  /** 批量删除 */
  async function onbatchDel(isBatch: boolean, ids: string) {
    // 返回当前选中的行
    let frmIDS;
    if (isBatch) {
      const curSelected = tableRef.value.getTableRef().getSelectionRows();
      // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
      const myIDS = JSON.stringify(getKeyList(curSelected, "id"));
      frmIDS = myIDS.substring(1, myIDS.length - 1);
      tableRef.value.getTableRef().clearSelection();
    } else {
      frmIDS = ids;
    }
    const Result = await delFormData({
      ids: frmIDS,
      tableName: form.editTable
    });

    if (Result.isSuccess) {
      message(`已删除编号为 ${frmIDS} 的数据`, {
        type: "success"
      });
      onSearch();
    } else {
      if (Result.msg == "" || Result.msg == null) {
        message("删除失败！", { type: "error" });
      } else {
        message(Result.msg, { type: "error" });
      }
    }
  }

  //打开表单编辑
  async function handleOpenData(ids: number, falg: number) {
    //falg=1表示新增，2表示修改,5表示当前记录不能修改
    myProp.rsID = ids;
    myProp.modeID = modeID;
    myProp.isSearch = ctrButton.isSearch;
    myProp.isSheng = ctrButton.isSheng;
    myProp.editCode = oneModel.value.editCode;
    myProp.tableName = form.appName;
    myProp.paretCode = parentCode.value;
    getFormFunList(ctrButton, falg, ids);
    if (falg == 5) {
      //如果是5表示已提交，用户不能在做任何操作。
      myProp.isSearch = true;
      formFunList = [];
    }
    addDialog({
      title: `表单编辑`,
      props: myProp,
      width: "80%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      center: true,
      alignCenter: true,

      footerButtons: formFunList,
      contentRenderer: () => h(editForm, { ref: editFormRef }),
      closeCallBack: async () => {
        //关闭后回调函数
        await onSearch();
      }
    });
  }

  //保存操作
  async function handleSaveData(val: string) {
    console.log(val, "保存");
  }

  const juese = ref([]);
  //执行表单函数
  async function exeFormFun(ids: string, funItem: any) {
    if (ids == "0") {
      // reqFun.ids = ids;
      const curSelected = tableRef.value.getTableRef().getSelectionRows();
      const myIDS = JSON.stringify(getKeyList(curSelected, "id"));
      juese.value = getKeyList(curSelected, "应用角色");
      reqFun.ids = myIDS.substring(1, myIDS.length - 1);
      // tableRef.value.getTableRef().clearSelection();
    } else {
      reqFun.ids = ids;
    }
    reqFun.funID = funItem.id;
    reqFun.contrlID = funItem.contrlFalg;
    //判断是采用输入的方式还是调用接口的方式
    const form = reactive({
      multStr: funItem.contrlTable
    });
    if (funItem.contrlTable.includes("$")) {
      const result = await getRolesList(form);
      if (result.isSuccess == true) {
        reqFun.contrText = result.result;
        console.log("角色" + result.result);
      }
    } else {
      reqFun.contrText = funItem.contrlTable;
    }

    if (juese.value != null && juese.value.length > 0) {
      reqFun.currText = juese.value.join(",");
    }
    reqFun.tableName = form.appName;
    if (funItem.contrlFalg == 1 || reqFun.contrlID == 4) {
      submitSaveData(reqFun);
    } else {
      //判断是否选中数据
      if (reqFun.ids == "") {
        message("请选择要操作的数据！", { type: "error" });
      } else {
        addDialog({
          title: `权限配置`,
          props: reqFun,
          width: "30%",
          draggable: true,
          fullscreenIcon: true,
          closeOnClickModal: false,
          center: true,
          alignCenter: true,
          footerButtons: [
            {
              label: "确定",
              type: "success",
              btnClick: ({ dialog: { options, index } }) => {
                //调用数据获取结果
                const Result = dialogRef.value.getReulst();
                if (Result.ids == "") {
                  message("请选择要操作的数据！", { type: "error" });
                } else {
                  submitSaveData(Result);
                  closeDialog(options, index);
                }
              }
            },
            {
              label: "取消",
              type: "success",
              btnClick: ({ dialog: { options, index } }) => {
                closeDialog(options, index);
              }
            }
          ],
          contentRenderer: () => h(dialog, { ref: dialogRef })
        });
      }
    }
  }

  //提交数据
  async function submitSaveData(reqFun: reqExeFun) {
    const Result = await exeFormFunApi(reqFun);
    if (Result.isSuccess) {
      message(Result.msg, {
        type: "success"
      });
      onSearch();
    } else {
      message(Result.msg, { type: "error" });
    }
  }

  //文件改变
  const fileOnChange = async file => {
    const reader = new FileReader();
    reader.readAsDataURL(file.raw);

    if (file.status === "ready") {
      fileUpload.value.clearFiles();
      formData.append("formFiles", file.raw);
      formData.append("tableName", form.editTable);

      const Result = await importData(formData);
      if (Result.isSuccess) {
        message(Result.msg, {
          type: "success"
        });
        onSearch();
      } else {
        message(Result.msg, { type: "error" });
      }
    }
  };

  //特殊导入
  const fileOnChangeExcle = async file => {
    const reader = new FileReader();
    reader.readAsDataURL(file.raw);

    if (file.status === "ready") {
      fileUploadExl.value.clearFiles();
      formData.append("formFiles", file.raw);
      formData.append("tableName", form.appName);

      const Result = await importExlData(formData);
      if (Result.isSuccess) {
        message(Result.msg, {
          type: "success"
        });
        onSearch();
      } else {
        message(Result.msg, { type: "error" });
      }
    }
  };

  //导入导出数据
  async function ImportAndExpoertData(falg: number) {
    if (falg == 1) {
      console.log("原导入数据，已注释...");
      //1表示导入数据
      /*
      const Result = await importData({ tableName: form.appName });
      if (Result.isSuccess) {
        message(Result.msg, {
          type: "success"
        });
        onSearch();
      } else {
        message(Result.msg, { type: "error" });
      }
      */
    } else {
      //表示导出数据
      const Result = await excelData({
        tableName: form.appName,
        modID: modeID.value
      });
      if (Result.isSuccess) {
        window.location.href = Result.msg;
      } else {
        message(Result.msg, { type: "error" });
      }
    }
  }
  //用于更新列表数据
  async function showSubList(subID, pareID, row) {
    if (subID == modeID.value) {
      return;
    }
    const oneK = links.value.filter(
      item => item.id == oneModel.value.oneModel.id
    );
    if (oneK.length != 0) {
      oneK[0].row = row;
    }
    msubID.value = subID;
    usubID.value = subID;
    init(msubID.value, pareID);
    /*
    if (pareID == -1) {
      init(msubID.value, oneK[0].parentID);
      
    } else { 
      console.log("PPP",pareID);
       init(msubID.value, pareID);
    }
      */
  }

  //远程排序
  async function sortChange({ column }) {
    form.sort = column.order == "ascending" ? true : false;
    form.sortName = column.property;
    onSearch();
  }

  return {
    pagination,
    sortChange,
    form,
    onSearch,
    dataList,
    columns,
    isData,
    handleCurrentChange,
    handleSizeChange,
    handleDelData,
    handleOpenData,
    handleSaveData,
    ctrButton,
    funList,
    filterList,
    onbatchDel,
    exeFormFun,
    getImage,
    ImportAndExpoertData,
    fileOnChange,
    fileOnChangeExcle,
    fileList,
    fileUpload,
    fileUploadExl,
    editCode,
    showSubList,
    links,
    msubID,
    isDown,
    currentRow
  };
}
